package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.AddressBook;
import com.itheima.entity.User;
import com.itheima.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook1")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    //保存地址
    @PostMapping
    public R<String> addAddressBook(@RequestBody AddressBook addressBook, HttpSession session){
        log.info("新添加的地址是："+addressBook.toString());
        Object user = session.getAttribute("user");
        log.info(user.toString());
        Long id = Long.parseLong(user.toString());
        addressBook.setUserId(id);
        addressBookService.save(addressBook);
        return R.success("添加成功！");
    }

    //获取地址列表
    @GetMapping("/list")
    public R<List<AddressBook>> getList(){
        List<AddressBook> list=addressBookService.list();
        return R.success(list);
    }

    //修改默认状态
    @PutMapping("/default")
    public R<List<AddressBook>> setDefault(@RequestBody User id){
        List<AddressBook> list=addressBookService.list();
        List<AddressBook> list1=new ArrayList<>();
        for (AddressBook a:
             list) {
            if(a.getId().toString().equals(id.getId().toString())){
                a.setIsDefault(1);
            }else {
                a.setIsDefault(0);
            }
            list1.add(a);
        }
        addressBookService.updateBatchById(list1);
        return R.success(list1);
    }

    //地址修改回显功能
    @GetMapping("/{id}")
    public R<AddressBook> selectById(@PathVariable Long id){
        AddressBook byId = addressBookService.getById(id);
        return R.success(byId);
    }

    //地址修改功能实现
    @PutMapping
    public R<String> modifyAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功！");
    }

    @DeleteMapping
    public R<String> deleteAddress(Long[] ids){
        for (Long id:
             ids) {
            addressBookService.removeById(id);
        }
        return R.success("删除成功！");
    }
}
